package com.beiding.render;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class MapUtils {


    //可以识别public字段和getter方法,getter方法优先级更高
    public static Map<String, Object> objectToMap(Object object) {
        if (object == null) {
            return null;
        }
        Map<String, Object> r = new HashMap<>();

        for (Field field : object.getClass().getFields()) {
            try {
                Object o = field.get(object);
                r.put(field.getName(), o);
            } catch (Exception ignore) {
            }
        }

        Set<Method> lastM = new HashSet<>();
        for (Method method : object.getClass().getMethods()) {
            if (method.getName().startsWith("get") && method.getParameterCount() == 0 && method.getName().length() > 3) {
                char c = method.getName().charAt(3);
                if (c >= 65 && c <= 90) {
                    lastM.add(method);
                } else {
                    try {
                        r.put(method.getName().substring(3), method.invoke(object));
                    } catch (Exception ignore) {

                    }
                }
            }
        }

        for (Method method : lastM) {
            try {
                String name = method.getName();
                String n = ((char) (name.charAt(3) + 32)) + (name.length() > 4 ? name.substring(4) : "");
                r.put(n, method.invoke(object));
            } catch (Exception ignore) {

            }
        }

        return r;
    }


}
